/*
 * Copyright 2007 - The JDPF Project Team (http://www.jdpf.org) 
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); 
 * you may not use this file except in compliance with the License. 
 * You may obtain a copy of the License at 
 * 
 * http://www.apache.org/licenses/LICENSE-2.0 
 * 
 * Unless required by applicable law or agreed to in writing, software 
 * distributed under the License is distributed on an "AS IS" BASIS, 
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and 
 * limitations under the License. 
 */
package org.jdpf.core.paramloader;

import java.io.IOException;
import java.net.URL;

import javax.xml.XMLConstants;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;

import org.jdpf.core.kernel.elements.Token;
import org.jdpf.core.kernel.logging.ILogger;
import org.jdpf.core.kernel.logging.LoggerFactory;
import org.jdpf.core.paramloader.service.ParamLoadingService;
import org.osgi.framework.BundleContext;
import org.xml.sax.SAXException;

public class ParamLoader implements ParamLoadingService, ParamParserListener {

	/**
	 * Logger for this class
	 */
	private static final ILogger logger = LoggerFactory.getDefault()
			.getLogger();

	private static final String PARAM_SCHEMA="JDPFParameters.xsd";
	
    private Token token;
	private SAXParserFactory factory;


	public ParamLoader(BundleContext bc){
		token=null;
		factory=SAXParserFactory.newInstance();
		factory.setNamespaceAware(true);
		SchemaFactory schemaFactory=SchemaFactory.newInstance(
									XMLConstants.W3C_XML_SCHEMA_NS_URI);
		Schema schema=null;
		try {
			URL f = (URL) bc.getBundle().findEntries("/", PARAM_SCHEMA, true).nextElement();
			schema = schemaFactory.newSchema(f);
			factory.setSchema(schema);
			factory.setValidating(true);
		} catch (Exception e) {
			logger.fatal(this, e.getMessage());
		}
	}

	public Token getParamToken() {
		return token;
	}

	public void load(String file) {
		token=null;

		try {
			SAXParser parser=factory.newSAXParser();
			parser.parse(file, new ParamEventHandler(this));
		} catch (ParserConfigurationException e) {
			logger.fatal(this, e.getMessage());
		} catch (SAXException e) {
			logger.fatal(this, e.getMessage());
		} catch (IOException e) {
			logger.fatal(this, e.getMessage());
		} 
	}

	public void endParsing(Token token) {
		this.token=token;
	}
}
